package com.gl.order.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gl.order.entity.CustomerInfo;
import com.gl.order.entity.dto.AddCustomerDto;
import com.gl.order.entity.dto.CustomerPageDto;
import com.gl.order.entity.dto.PageDto;
import com.gl.order.entity.vo.CustomerCompanyVo;
import com.gl.order.entity.vo.CustomerPageVo;
import com.gl.order.entity.vo.CustomerVo;
import com.gl.order.entity.vo.ShippingAddressVo;
import com.gl.order.mapper.CustomerAddressRefMapper;
import com.gl.order.mapper.CustomerInfoMapper;
import com.gl.order.security.model.SecurityUser;
import com.gl.order.service.CustomerService;
import com.gl.order.service.ShippingAddressService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author: liangSY
 * @Date: 2021/6/27
 * @ClassName: CustomerServiceImpl
 * @Description: CustomerServiceImpl描述
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CustomerServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerService {

    ShippingAddressService addressService;

    CustomerAddressRefMapper customerAddressRefMapper;

    public CustomerServiceImpl(ShippingAddressService addressService, CustomerAddressRefMapper customerAddressRefMapper) {
        this.addressService = addressService;
        this.customerAddressRefMapper = customerAddressRefMapper;
    }

    @Override
    public CustomerVo findById(String id) {
        CustomerVo vo = baseMapper.findById(id);
        // 获取地址
        List<ShippingAddressVo> addresses = addressService.findByCustomerId(id);
        vo.setAddresses(addresses);
        return vo;
    }

    @Override
    public IPage<CustomerVo> customerPageByMarket(CustomerPageDto dto) {
        Page<CustomerVo> page = new Page<>(dto.getPageNo(), dto.getPageSize());
        IPage<CustomerVo> customers = baseMapper.customerPageByMarket(page, dto);
        //验证获取数据是否为空
        List<CustomerVo> vos = customers.getRecords();
        List<String> customerIds = vos.stream().map(CustomerVo::getId).collect(Collectors.toList());
        if (null == customerIds || customerIds.size() == 0) {
            return customers;
        }
        //获取客户的收货地址
        List<ShippingAddressVo> addresses = addressService.findByCustomer(customerIds);
        Map<String, List<ShippingAddressVo>> map = addresses.stream().collect(Collectors.groupingBy(ShippingAddressVo::getCustomerId));
        vos.stream().forEach(a -> {
            List<ShippingAddressVo> list = map.containsKey(a.getId()) ? map.get(a.getId()) : new ArrayList<>();
            if (StringUtils.equals(a.getId(), dto.getCustomerId())) {
                Optional<ShippingAddressVo> op = list.stream().filter(ad -> StringUtils.equals(ad.getId(), dto.getAddressId())).findFirst();
                a.setAddressName(op.isPresent() ? op.get().getAddress() : "");
            }
            a.setAddresses(list);
        });
        return customers;
    }

    @Override
    public void add(AddCustomerDto dto) {
        CustomerInfo customerInfo = new CustomerInfo();
        BeanUtils.copyProperties(dto,customerInfo);
        customerInfo.setDel(false);
        SecurityUser principal = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        customerInfo.setCreator(principal.getCurrentUserInfo().getId());
        save(customerInfo);
    }

    @Override
    public IPage<CustomerPageVo> getList(PageDto dto, String marketUser) {
        Page<CustomerPageVo> page = new Page<>(dto.getPageNo(),dto.getPageSize());
        return this.baseMapper.getCustomerPageData(page, marketUser);
    }

    @Override
    public boolean delCustomer(String id) {
      // 为删除客户，避免删除导致订单详情页显示不正常
        CustomerInfo info = getById(id);
        Assert.notNull(info,"数据不存在！");
        // TODO 如果客户有进行中的单，不能删除客户，详情需要结合节点数据进行判断
        info.setDel(true);
        updateById(info);
        return false;
    }

}
